﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Windows.Media.Imaging;
using System.Threading;

namespace FixedEyes3
{
    public partial class MainPage : UserControl
    {
        CaptureSource captureSource;
        WriteableBitmap bitmap;
        ImageComparer imageComparer;
        int listBoxItem = 100;
        int commandListItem = 2;
        int pixelsTop = 0;
        int pixelsBottom = 0;
        int pixelsLeft = 0;
        int pixelsRight = 0;
        int cursorX = 640 / 2;
        int cursorY = 480 / 2;

        public MainPage()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            captureSource = new CaptureSource();
            captureSource.VideoCaptureDevice =
                (VideoCaptureDevice)CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice();

            imageComparer = new ImageComparer(0, 0, 0);

            //for (int i = 0; i < 500; i++)
            //    listBox1.Items.Add("Silverlight" + i.ToString());

            //commandList.Items.Add("Assistance");
            //commandList.Items.Add("Doctor");
            //commandList.Items.Add("Nurse");
        }

        // захват видеопотока с веб-камеры
        private void btnCapture_Click(object sender, RoutedEventArgs e)
        {
            // получаем разрешение и начинаем процесс захвата
            if (CaptureDeviceConfiguration.AllowedDeviceAccess ||
                CaptureDeviceConfiguration.RequestDeviceAccess())
            {
                captureSource.Start();
            }

            captureSource.CaptureImageCompleted += new EventHandler<CaptureImageCompletedEventArgs>(captureSource_CaptureImageCompleted);
            var dispatcherTimer = new DispatcherTimer();
            dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 40);    // 25 кадров в секунду
            dispatcherTimer.Tick += (s, t) =>
            {
                captureSource.CaptureImageAsync();
            };
            dispatcherTimer.Start();
        }

        void captureSource_CaptureImageCompleted(object sender, CaptureImageCompletedEventArgs e)
        {
            InitializeValues();

            Brush blueBrush = new SolidColorBrush(Colors.Blue);

            e.Result.DrawRectangle(450, 250, 480, 280, Colors.Red);
            BitmapSource bitmapSource = e.Result;
            ImageBrush brush = new ImageBrush();
            brush.ImageSource = bitmapSource;
            webCamVideo.Fill = brush;

            bitmap = e.Result;
            imageComparer.Compare(bitmap);

            pixelsBottom = imageComparer.RightBottomCount + imageComparer.LeftBottomCount;
            pixelsTop = imageComparer.RightTopCount + imageComparer.LeftTopCount;
            pixelsRight = imageComparer.RightBottomCount + imageComparer.RightTopCount;
            pixelsLeft = imageComparer.LeftBottomCount + imageComparer.LeftTopCount;

            if (pixelsBottom < pixelsTop)
            {
                // во избежание выхода массива за нижнюю границу
                if (listBoxItem < 500)
                    listBoxItem += 10;

                if (commandListItem < 2)
                    commandListItem++;

                if (cursorY < 440)
                {
                    cursorY += (int)Math.Ceiling(pixelsBottom / 3);
                }

                if (imageComparer.LeftBottomCount < imageComparer.RightBottomCount)
                {
                    bottomLeftPanel.Background = blueBrush;
                }
                else if (imageComparer.LeftBottomCount > imageComparer.RightBottomCount)
                {
                    bottomRightPanel.Background = blueBrush;
                }
            }
            else if (pixelsBottom > pixelsTop)
            {
                // во избежание выхода массива за верхнюю границу
                if (listBoxItem > 40)
                    listBoxItem -= 10;

                if (commandListItem > 0)
                    commandListItem -= 1;

                if (cursorY > 0)
                {
                    cursorY -= (int)Math.Ceiling(pixelsTop / 3);
                }

                if (imageComparer.LeftBottomCount < imageComparer.RightBottomCount)
                {
                    topLeftPanel.Background = blueBrush;
                }
                else if (imageComparer.LeftBottomCount > imageComparer.RightBottomCount)
                {
                    topRightPanel.Background = blueBrush;
                }
            }
            if (pixelsRight < pixelsLeft)
            {
                if (cursorX < 600)
                {
                    cursorX += (int)Math.Ceiling(pixelsLeft / 3);
                }
            }
            else if (pixelsRight > pixelsLeft)
            {
                if (cursorX > 40)
                {
                    cursorX -= (int)Math.Ceiling(pixelsRight / 3);
                }
            }

            //listBox1.ScrollIntoView(listBox1.Items[listBoxItem]);
            //commandList.ScrollIntoView(commandList.Items[commandListItem]);
            //e.Result.FillRectangle(cursorX - 30, cursorY - 30, cursorX + 30, cursorY + 30, Colors.Green);
        }

        private void InitializeValues()
        {
            bottomRightPanel.Background = null;
            bottomLeftPanel.Background = null;
            topRightPanel.Background = null;
            topLeftPanel.Background = null;
        }

        private void webCamVideo_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            Point location = e.GetPosition(webCamVideo);
            imageComparer = new ImageComparer(bitmap.GetPixel((int)location.X, (int)location.Y).R, bitmap.GetPixel((int)location.X, (int)location.Y).G,
                bitmap.GetPixel((int)location.X, (int)location.Y).B);
        }
    }
}
